<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>JS2APP</title>
    <style>
        input{
            color: red;
            font-size: 18px;
            padding: 10px;
            margin: 4px;
        }
    </style>
</head>
<body>
<input id="share" type="button" value="share">
<input id="setShareContent" type="button" value="setShareContent">
<input id="setShareContent2" type="button" value="setShareContent(指定渠道）">
<input id="storgeQRcode" type="button" value="storgeQRcode(链接方式)保存图片到本地">
<input id="storgeQRcode2" type="button" value="storgeQRcode2保存图片到本地">
<input id="getLyfCode" type="button" value="getLyfCode(来伊份授权登录)">
<input id="getLyfCode1" type="button" value="getLyfCode(来伊份授权登录 无效)">
<input id="saveImages" type="button" value="批量并保存图片">
<IMG  id="imgtest" src="https://yun.duiba.com.cn/DS-tech/lb_tech/WechatIMG341.jpeg">
<input id="hideTitleBar01" type="button" value="隐藏显示原生头 隐藏">
<input id="hideTitleBar02" type="button" value="隐藏显示原生头 显示">
<input id="getTitleBarTopHeight" type="button" value="获取原生电池状态栏高度，返回">
<input id="finishWebview" type="button" value="结束当前webview">
<input id="selectContact" type="button" value="获取通讯录，处理权限，选择并回调 手机号，姓名">
<input id="isExistContactinput" type="text" value="15038267031">
<input id="isExistContact" type="button" value="查询手机号是否在通讯录中，处理权限，结果回调 是否存在">
<input id="searchContact" type="text" value="150">

<input id="jumpIMGroup" type="button" value="提供群id,原生跳转群页面">
<input id="selectAddress" type="button" value="选地址（登录后才能调用）">

<input id="hideShare01" type="button" value="隐藏分享图标，右边直接为叉按钮 隐藏">
<input id="hideShare02" type="button" value="隐藏分享图标，右边直接为叉按钮 显示">
<input id="backGroundEvent" type="button" value="App回到后台或前台事件接口">
<input id="getDeviceInfo" type="button" value="获取App设备信息（手机品牌，型号，屏幕宽高">
<input id="registerBackListener" type="button" value="注册其他页面回来监听">
<input id="clearBackListener" type="button" value="清空注册其他页面回来监听">
<a href="lyf://h5?body={'url':'http://www.laiyifen.com'}"> test下级页面</a>

<hr/>

<input id="StatusBarLight" type="button" value="设置状态栏Light模式">
<input id="StatusBarDark" type="button" value="设置状态栏Dark模式">
<!--<input id="storgeQRcode2" type="button" value="storgeQRcode(图片方式)">-->
<!--原生给H5提供方法：
1. 隐藏显示原生头
2. 获取原生电池状态栏高度，返回
3. 结束当前webview
4. 获取通讯录，处理权限，选择并回调
5. 查询手机号是否在通讯录中，处理权限，结果回调
6. 提供群id,原生跳转群页面
7. 隐藏分享图标，右边直接为叉按钮
8. App回到后台或前台事件接口
9. 获取App设备信息（手机品牌，型号，屏幕宽高）-->

<script type="text/javascript">
    document.getElementById('hideTitleBar01').onclick= function () {
        var message = {
            'function': 'hideTitleBar',
            'param': {
                'hide': true
            },
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('selectAddress').onclick= function () {
        var message = {
            'function': 'selectAddress',
            'param': {
                'selecttype': 3
            },
            'callback': 'callresult',
        };
       /* lyf://selectAddress?body={"selecttype":1}
//selecttype，0 查看（可不传），1，商城选择地址并保存选中，2,外卖选地址，3，选择地址返回id*/
        //返回callback addressid
        appMessage(message);
    }
    document.getElementById('registerBackListener').onclick= function () {
        var message = {
            'function': 'registerBackListener',
            'callback': 'callresult',
        };
        appMessage(message);
    }

    document.getElementById('StatusBarLight').onclick = function () {
        var message = {
            'function': 'StatusBarModel',
            'param': {
                'model': "light"
            },
        };
        appMessage(message);
    }

    document.getElementById('StatusBarDark').onclick = function () {
        var message = {
            'function': 'StatusBarModel',
            'param': {
                'model': "dark"
            },
        };
        appMessage(message);
    }

    document.getElementById('clearBackListener').onclick= function () {
        var message = {
            'function': 'clearBackListener'
        };
        appMessage(message);
    }
    document.getElementById('hideTitleBar02').onclick= function () {
        var message = {
            'function': 'hideTitleBar',
            'param': {
                'hide': false
            },
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('getTitleBarTopHeight').onclick= function () {
        var message = {
            'function': 'getTitleBarTopHeight',
            'callback': 'callresult',
        };
        // 返回 高度值
        appMessage(message);
    }
    document.getElementById('finishWebview').onclick= function () {
        var message = {
            'function': 'finishWebview',
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('selectContact').onclick= function () {
        var message = {
            'function': 'selectContact',
            'callback': 'callresult',
        };
        /*
        返回json
        {"phone":"15038267031",
        "username":"姓名" }
        */
        appMessage(message);
    }
    document.getElementById('isExistContact').onclick= function () {
        var input_text=document.getElementById('isExistContactinput');
        var message = {
            'function': 'isExistContact',
            'param': {
                'phone': input_text.value
            },
            'callback': 'callresult',
        };
        console.log(JSON.stringify(message));
        // 返回 true/false
        appMessage(message);
    }
    var elementById = document.getElementById('searchContact');
    elementById.oninput= function () {
        console.log(" value"+elementById.value);
        var message = {
            'function': 'searchContact',
            'param': {
                'text': elementById.value
            },
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('jumpIMGroup').onclick= function () {
        var message = {
            'function': 'jumpIMGroup',
            'param': {
                'groupid': '1234567'
            },
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('hideShare01').onclick= function () {
        var message = {
            'function': 'hideShare',
            'param': {
                'hide': true
            },
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('hideShare02').onclick= function () {
        var message = {
            'function': 'hideShare',
            'param': {
                'hide': false
            },
            'callback': 'callresult',
        };
        appMessage(message);
    }
    document.getElementById('backGroundEvent').onclick= function () {
        var message = {
            'function': 'backGroundEvent',
            'callback': 'callresult',
        };

        appMessage(message);
    }
    document.getElementById('getDeviceInfo').onclick= function () {
        var message = {
            'function': 'getDeviceInfo',
            'callback': 'callresult',
        };

        /*
        返回json
        {"screenWidth":1080,
        "screenHeight":1234,
        "manufacturer":"xiaomiMix2",
        "OS":"android 9",
        "appVersion":"7.1.20" }
        */
        appMessage(message);
    }
    document.getElementById('share').onclick= function () {
        var message = {
            'function': 'share',
            'param': {
                'url': 'https://m.laiyifen.com/group/detail.html?patchGrouponId=3000000000000126&mpId=1009090701000015&shareCode=f4ec31471fce4765a45ab9f53c2b311a',
                'title': '【拼团】巴旦木酥饼（原味）220g',
                'description': '巴旦木酥饼（原味）220g',
                'url160x160': 'https://static2.laiyifen.com/files/product/image/1553657709810_3777.jpg',
                'pic': 'https://static2.laiyifen.com/files/product/image/1553657709810_3777.jpg',
                'isMiniProgram': true,
                'originalId': 'gh_4a4a36db4c12',
                'miniProgramPage': '/pages/detail/index?id=3000000000000126&mpId=1009090701000015'
            },
            'callback': 'callresult',
            "shareSelectItem": "shareSelectItem",
            "dialogvisibility": "dialogvisibility"
        };
        appMessage(message);
    }
    document.getElementById('setShareContent').onclick= function () {
        var setShareContent = {
            "function": "setShareContent",
            "param": {
                "url": "http://m.laiyifen.com/ouser-center/duiba/autoLogin.do",
                "title": "积分当钱花，零食0元购",
                "description": "积分兑好物，各种优惠券、零食，生活服务、精选商品等你来兑换",
                "url160x160": "https://yun.duiba.com.cn/DS-tech/lb_tech/WechatIMG341.jpeg",
                "pic": "https://yun.duiba.com.cn/DS-tech/lb_tech/WechatIMG341.jpeg"
            },
            "callback": "callresult",
            "shareSelectItem": "shareSelectItem",
            "dialogvisibility": "dialogvisibility"
        }
        appMessage(setShareContent);
    }
    document.getElementById('setShareContent2').onclick= function () {
        var setShareContent2 = {
            "function": "setShareContent",
            "param": {
                "url": "https://m.laiyifen.com/goods/offlineStore/detail?storeCode=1904&storeName=%E4%B8%8A%E6%B5%B7%E5%B8%82%E9%97%B5%E8%A1%8C%E5%8C%BA%E5%8F%A4%E7%BE%8E%E8%A5%BF%E8%B7%AF%E4%B8%89%E5%BA%97",
                "title": "上海市闵行区古美西路三店",
                "description": "嘿，我发现了一家很好吃的零食店，分享给你，快去看看有什么优惠吧～",
                "posterUrl": "https://m.laiyifen.com/goods/offlineStore/poster?storeName=%E4%B8%8A%E6%B5%B7%E5%B8%82%E9%97%B5%E8%A1%8C%E5%8C%BA%E5%8F%A4%E7%BE%8E%E8%A5%BF%E8%B7%AF%E4%B8%89%E5%BA%97&storeAddress=%E9%97%B5%E8%A1%8C%E5%8C%BA%E5%8F%A4%E7%BE%8E%E8%A5%BF%E8%B7%AF260%E5%8F%B7%E7%AC%AC1%E5%B9%A2-6%E5%AE%A4&storeCode=1904",
                "channel": ["IM", "Poster", "WechatMoments", "Wechat", "QQ", "QZone"],
                "sharePicUrl": "https://static.laiyifen.com/goods-static/images/offlineShare.png"
            },
            "callback": "callresult",
            "shareSelectItem": "shareSelectItem",
            "dialogvisibility": "dialogvisibility"
        }
        appMessage(setShareContent2);
    }

    document.getElementById('saveImages').onclick= function () {
        var saveImages = {
            "function": "saveImages",
            "param": {
                "images": ["https://static4.laiyifen.com/files/product-admin-web/image/1579744777302_5026.jpg",
                    "https://static3.laiyifen.com/files/product-admin-web/image/1579744785293_4889.jpg",
                    "https://static1.laiyifen.com/files/product-admin-web/image/1579744780267_9742.jpg",
                    "https://static2.laiyifen.com/files/product-admin-web/image/1579744782883_1570.jpg",
                    "https://static2.laiyifen.com/files/product-admin-web/image/1579744787907_4870.jpg"],
            },
            "callback": "callresult"
        }
        appMessage(saveImages);
    }
    document.getElementById('storgeQRcode').onclick= function () {
        getUrlBase64('https://yun.duiba.com.cn/DS-tech/lb_tech/WechatIMG341.jpeg', 'jpg', function (base64) {
            console.log(base64);//base64编码值
            var storgeQRcode = {
                "function": "storgeQRcode", "param": {
                    "imgUrl": base64 ,
                },
                "callback": "callresult"
            }
            appMessage(storgeQRcode);
        });
    }

    document.getElementById('storgeQRcode2').onclick= function () {
        var ext= getImageBase64(document.getElementById('imgtest'), 'jpg' );
        var storgeQRcode = {
            "function": "storgeQRcode", "param": {
                "imgUrl":  ext,
            },
            "callback": "callresult"
        }
        appMessage(storgeQRcode);
    }

    document.getElementById('getLyfCode').onclick= function () {
        var getLyfCode = {
            "function": "getLyfCode",
            "param": {
                //appid
                "appid": "46B8461B15104819B8C89CEE1FE3DAE2",
            },
            //结果回调，{"code":"1","data":"lyfcode"}
            // code==1 成功返回，
            // code ==2 用户拒绝,
            // code==-1 非法appid（无效的授权商户）
            // code==-2 参数错误
            // code==-3 服务器错误
            "callback": "callresult"
        }
        appMessage(getLyfCode);
    }
    document.getElementById('getLyfCode1').onclick= function () {
        var getLyfCode = {
            "function": "getLyfCode",
            "param": {
                //appid
                "appid": "abc",
            },
            //结果回调，{"code":"1","data":"lyfcode"}
            // code==1 成功返回，
            // code ==2 用户拒绝,
            // code==-1 非法appid（无效的授权商户）
            // code==-2 参数错误
            // code==-3 服务器错误
            "callback": "callresult"
        }
        appMessage(getLyfCode);
    }


    function callresult(result) {
        // alert('结果：'+json2str(result));
        alert('结果：'+JSON.stringify(result));
    }

    function shareSelectItem(result) {
        // alert('结果：'+json2str(result));
        alert('shareSelectItem：' + JSON.stringify(result));
    }

    function dialogvisibility(result) {
        //show 1 hide 0
        alert('dialogvisibility：'+result );
    }
    /**
     *
     * @param img html的img标签
     * @param ext 图片格式
     * @returns {string}
     */
    function getImageBase64(img, ext) {
        var canvas = document.createElement("canvas");   //创建canvas DOM元素，并设置其宽高和图片一样
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height); //使用画布画图
        var dataURL = canvas.toDataURL("image/" + ext);  //返回的是一串Base64编码的URL并指定格式
        canvas = null; //释放
        return dataURL;
    }

    /**
     *
     * @param url 图片路径
     * @param ext 图片格式
     * @param callback 结果回调
     */
    function getUrlBase64(url, ext, callback) {
        var canvas = document.createElement("canvas");   //创建canvas DOM元素
        var ctx = canvas.getContext("2d");
        var img = new Image;
        img.crossOrigin = 'Anonymous';
        img.src = url;
        img.onload = function () {
            canvas.height = 392; //指定画板的高度,自定义
            canvas.width = 363; //指定画板的宽度，自定义
            ctx.drawImage(img, 0, 0, 363, 392); //参数可自定义
            var dataURL = canvas.toDataURL("image/" + ext);
            callback.call(this, dataURL); //回掉函数获取Base64编码
            canvas = null;
        };
    }

    function appMessage(obj) {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('android') > -1 || u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isAndroid) {
            console.log(JSON.stringify(obj));
            str = String(JSON.stringify(obj));
            //android用的是对象转json转String   mobileAPI为原生注册的  addJavascriptInterface(javaToH5Api, "mobileAPI");
            window.mobileAPI.postMessage(str);
        } else if (isiOS) {
            //ios的用的是对象
            window.webkit.messageHandlers.mobileAPI.postMessage(obj);
        }
    };

    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?0c20bbce3f1bd24d17d0d46e432a39fa";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
</script>
</body>
</html>
